<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import TnForm from '@tuniao/tnui-vue3-uniapp/components/form/src/form.vue'
import TnFormItem from '@tuniao/tnui-vue3-uniapp/components/form/src/form-item.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnImageUpload from '@tuniao/tnui-vue3-uniapp/components/image-upload/src/image-upload.vue'
import TnRadio from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio.vue'
import TnRadioGroup from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio-group.vue'
import TnCheckbox from '@tuniao/tnui-vue3-uniapp/components/checkbox/src/checkbox.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import type {
  FormRules,
  ImageUploadCustomCallbackFunction,
  TnFormInstance,
} from '@tuniao/tnui-vue3-uniapp'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import PageContainer from '@/components/page-container/index.vue'
import {
  FILE_URL,
  MP_API_URL,
  SYSTEM_CONFIG,
  USER_TOKEN,
} from '@/api/config.js'
import circles from '@/api/circles.js'

const formRef = ref<TnFormInstance>()
// 导航栏的高度
const navbarHeight = ref(0)
// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}

const items = reactive({
  agent: false,
  systemConfig: {
    circles: {
      checkin_fillin_wechat_id: 0,
    },
    agreement: {
      circles_create_agreement: '',
    },
  },
  loading: false,
  userToken: '',
  imageList: [],
})

const uploadCallbackHandle: ImageUploadCustomCallbackFunction = (
  data: UniApp.UploadFileSuccessCallbackResult
) => {
  const resData = JSON.parse(data.data)
  console.log(resData, 'images')
  if (resData.code == 1) {
    items.imageList.push(resData.data.file.url)
    formData.image = items.imageList.join(',')
    console.log(formData.image, 'images2')
    return FILE_URL + resData.data.file.url
  }
}

onMounted(() => {
  getCirclesType()
  items.systemConfig = uni.getStorageSync(SYSTEM_CONFIG)
  items.userToken = uni.getStorageSync(USER_TOKEN)
})

const getCirclesType = () => {
  circles
    .circlesType()
    .then((res) => {
      vueVersionPickerData.value = res.data
    })
    .catch((err) => {
      console.log(err)
    })
}

// 打开地图选择位置
const clickChooseLocation = () => {
  uni.chooseLocation({
    success(res) {
      formData.location = res.name
      formData.poiaddress = res.address
      formData.longitude = res.longitude
      formData.latitude = res.latitude
    },
  })
}

// 表单数据
const formData = reactive({
  name: '',
  image: '',
  circles_type_id: 0,
  introduce: '',
  location: '',
  poiaddress: '',
  longitude: '',
  latitude: '',
  wechat_id: '',
})

const formRules: FormRules = {
  image: [
    { required: true, message: '请上传圈子图片', trigger: ['change', 'blur'] },
  ],
  name: [
    { required: true, message: '请输入圈子名称', trigger: ['change', 'blur'] },
  ],
  introduce: [
    {
      required: true,
      message: '请介绍一下圈子吧',
      trigger: ['change', 'blur'],
    },
  ],
  circles_type_id: [
    { required: true, message: '请选择圈子类型', trigger: ['change', 'blur'] },
  ],
}

// 圈子类型选择
const vueVersionPickerData = ref([])

/* 提交表单 */
const submitForm = () => {
  if (items.agent == false) {
    uni.showToast({
      title: '请勾选并同意《圈子创建协议》',
      duration: 3000,
      icon: 'none',
    })
    return
  }

  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      console.log(formData, 'formData')
      items.loading = true
      circles
        .circlesApply(formData)
        .then((res) => {
          console.log(res, 'resres')
          uni.showToast({
            title: res.msg,
            duration: 3000,
            icon: 'none',
          })
          if (res.code == 1) {
            items.loading = false
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/index/index',
              })
            }, 3000)
          }
        })
        .catch((err) => {
          console.log(err)
          uni.showToast({
            title: '提交失败',
            icon: 'error',
          })
        })
    } else {
      uni.showToast({
        title: '表单校验失败',
        icon: 'none',
      })
    }
  })
}
</script>

<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      :bottom-shadow="false"
      :placeholder="false"
      :z-index="999"
      @init-finish="navbarInitFinishHandle"
    >
      创建圈子
    </TnNavbar>
    <view
      class="form-container"
      :style="{ paddingTop: `${navbarHeight + 10}px` }"
    >
      <TnForm
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="150"
        label-position="top"
      >
        <TnFormItem label="圈子logo" prop="image" label-position="left">
          <TnImageUpload
            v-model="items.imageList"
            :limit="1"
            :show-error-tips="false"
            :action="MP_API_URL + '/system.System/upload'"
            :header="{
              Authorization: items.userToken,
            }"
            :custom-upload-callback="uploadCallbackHandle"
          />
        </TnFormItem>
        <TnFormItem label="圈子名称" prop="name">
          <TnInput v-model="formData.name" clearable />
        </TnFormItem>
        <TnFormItem label="圈子介绍" prop="introduce">
          <TnInput
            v-model="formData.introduce"
            type="textarea"
            height="200"
            :maxlength="200"
            :show-word-limit="true"
            placeholder="请介绍一下圈子吧"
          />
        </TnFormItem>
        <TnFormItem label="请选择圈子类型" props="circles_type_id">
          <TnRadioGroup v-model="formData.circles_type_id">
            <span v-for="(item, index) in vueVersionPickerData" :key="index">
              <TnRadio border :label="item.id">{{ item.name }}</TnRadio>
            </span>
          </TnRadioGroup>
        </TnFormItem>
        <TnFormItem label="圈子位置" prop="poiaddress">
          <TnInput
            v-model="formData.poiaddress"
            :disabled="true"
            placeholder="请选择圈子位置"
          >
            <template #suffix>
              <TnButton
                text
                :custom-style="{ padding: '0 10rpx' }"
                @click="clickChooseLocation"
              >
                <TnIcon name="location" size="35rpx" />选择
              </TnButton>
            </template>
          </TnInput>
        </TnFormItem>
        <TnFormItem
          label="圈主微信"
          prop="wechat_id"
          v-if="items.systemConfig.circles.checkin_fillin_wechat_id == 'on'"
        >
          <TnInput
            v-model="formData.wechat_id"
            clearable
            placeholder="请填写圈主微信号"
          />
        </TnFormItem>
      </TnForm>
    </view>
    <view class="tn-ml tn-mb tn-flex tn-flex-row items-center">
      <TnCheckbox v-model="items.agent" />
      <p class="tn-ml-xs">我已阅读并同意</p>
      <TnButton
        text
        @click="
          tnNavPage(items.systemConfig.agreement.circles_create_agreement)
        "
        >《圈子创建协议》</TnButton
      >
    </view>
    <view class="tn-flex-center">
      <TnButton
        size="xl"
        width="60%"
        shape="round"
        :loading="items.loading"
        @click="submitForm"
      >
        提交申请
      </TnButton>
    </view>
  </PageContainer>
</template>

<style lang="scss" scoped>
@use './styles/create.scss';
</style>
